package history

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"io"

	//"sync"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MHistory struct {
	Url            string
	State          string
	Md5            string
	LastModifyTime time.Time
}
type MongodbHistory struct {
	//locker *sync.Mutex
}

func NewMongodbHistory() *MongodbHistory {
	return &MongodbHistory{} //locker: new(sync.Mutex)}
}
func (this *MongodbHistory) GetRegisteredCount() int64 {

	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(ctx)

	// 获取数据库,获取集合
	c := client.Database("go_spider").Collection("History")

	// 存储数据

	count, err := c.CountDocuments(ctx, nil)

	if err != nil {
		println(err.Error())
		panic(err)
	}
	return int64(count)
}
func (this *MongodbHistory) Close() {

}
func (this *MongodbHistory) Register(url string) bool {
	var result bool = false
	//this.locker.Lock()
	//defer this.locker.Unlock()
	t := md5.New()
	io.WriteString(t, url)

	urlMd5 := hex.EncodeToString(t.Sum(nil))
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(ctx)

	// 获取数据库,获取集合
	c := client.Database("go_spider").Collection("History")

	count, err := c.CountDocuments(ctx, bson.M{"md5": urlMd5})
	if err != nil {
		panic(err)
	}

	if count > 0 {
		result = true
	} else {
		history := &MHistory{Url: url, Md5: urlMd5, State: Pending, LastModifyTime: time.Now()}

		_, err = c.InsertOne(ctx, history)

		if err != nil {
			panic(err)
		}
		result = false
	}
	return result
}
func (this *MongodbHistory) Update(url string, state string, lastModifyTime time.Time) {
	//this.locker.Lock()
	//defer this.locker.Unlock()
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(ctx)
	t := md5.New()
	io.WriteString(t, url)

	urlMd5 := hex.EncodeToString(t.Sum(nil))
	// 获取数据库,获取集合
	c := client.Database("go_spider").Collection("History")

	colQuerier := bson.M{"md5": urlMd5}
	change := bson.M{"$set": bson.M{"State": state, "LastModifyTime": lastModifyTime}}
	_, err = c.UpdateOne(ctx, colQuerier, change)
	if err != nil {
		panic(err)
	}
}
